package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Package;
import softswitch.model.Provider;
import softswitch.model.ProviderRate;
import softswitch.model.Route;


@Stateless
public class ProviderRateService {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public ProviderRate getById(Integer id){	
		return em.find(ProviderRate.class, id);
	}
    
    public ProviderRate save(ProviderRate providerRate) {
    	em.persist(providerRate); 
    	return providerRate;
    }
    
    public ProviderRate update(ProviderRate providerRate) {
    	return em.merge(providerRate); 
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(ProviderRate.class, id));	
    }
    
	@SuppressWarnings("unchecked")
    public List<Package> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM ProviderRate e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
    	if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    //----------------------------------------------------------------------
    
	@SuppressWarnings("unchecked")
	public List<ProviderRate> listByProvider(Provider provider) {
    	List<ProviderRate> results = null;
    	Query query = em.createQuery("SELECT e FROM ProviderRate e WHERE e.provider=:provider");
    	query.setParameter("provider", provider);
    	try{
    		results = query.getResultList();
    	}
    	catch(NoResultException e){
    	}
        return results; 
    }
	
	public ProviderRate getByRoute(Provider provider, Route route) {
    	ProviderRate result = null;
    	Query query = em.createQuery("SELECT e FROM ProviderRate e WHERE e.provider=:provider AND e.route=:route");
    	query.setParameter("provider", provider);
    	query.setParameter("route", route);
    	try{
    		result = (ProviderRate) query.getSingleResult();
    	}
    	catch(NoResultException e){
    	}
        return result; 
    }
    
    
}

